// pages/pay/pay.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseURL: 'http://43.139.97.111:8080',
    haveAddress: false,
    haveCoupon: false,
    userId: 22,
    userInfo: {},
    totalMoney: '',//最终总价
    firstTotalMoney: '',//首次总价
    reduceMoney: '0',
    firstReduceMoney: '优惠券',
    paylist: [],
    showIndex: null,//打开弹窗的对应下标
    height: '',//屏幕高度
    userCoupon: [10],
    temp: '',
    couponlist: [],
    selectCoupon: [],
    address: [],
    addressList: [],
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var _this = this
    const userinfo = wx.getStorageSync("userInfo");
    this.setData({
      userInfo: userinfo
    });
    console.log(_this.data.userInfo.userId)
    console.log(JSON.parse(options.paylist))
    _this.setData({
      paylist: JSON.parse(options.paylist),
      totalMoney: options.totalMoney,
      firstTotalMoney: options.totalMoney
    })
    _this.getConponId()
    _this.getAddress()
  },
  /**
  * 生命周期函数--监听页面显示
  */
  onShow() {
    var _this = this
    const userinfo = wx.getStorageSync("userInfo");
    this.setData({
      userInfo: userinfo
    });
    console.log(_this.data.userInfo.userId)

    _this.getConponId()
    _this.getAddress()
  },
  /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady() {
    var that = this;
    // 动态获取屏幕高度
    wx.getSystemInfo({
      success: (result) => {
        that.setData({
          height: result.windowHeight
        });
      },
    })
  },


  bindCheckbox: function (e) {
    var that = this;
    const idx = e.currentTarget.dataset.index;
    let userCoupon = that.data.userCoupon;
    const isSelect1 = userCoupon[idx].isSelect;
    userCoupon[idx].isSelect = !isSelect1;
    that.setData({
      userCoupon: userCoupon,
    });
  },

  // 打开弹窗
  openPopup(e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      showIndex: index
    })
  },
  //关闭弹窗
  closePopup() {
    this.setData({
      showIndex: null
    })
  },
  //确定使用
  useCoupon() {
    var _this = this;
    let userCoupon = _this.data.userCoupon;
    let couponlist = _this.data.couponlist;
    let firstTotalMoney = _this.data.firstTotalMoney;
    let reduceMoney = 0;
    let selectItem = [];
    var j = 0
    for (var i = 0; i < userCoupon.length; i++) {
      if (userCoupon[i].isSelect) {
        selectItem[j] = userCoupon[i];
        //获取对应id
        for (var y = 0; y < couponlist.length; y++) {
          if (userCoupon[i].couponId == couponlist[y].couponId) {
            selectItem[j].id = couponlist[y].id
          }
        }
        //计算折扣价格
        reduceMoney += selectItem[j].couponValue;
        j++;
      }
    }
    firstTotalMoney = firstTotalMoney - reduceMoney;
    //优惠超出判断
    if (firstTotalMoney <= 0) {
      firstTotalMoney = 0.01
    }
    _this.setData({
      selectCoupon: selectItem,
      reduceMoney: reduceMoney.toFixed(2),
      totalMoney: firstTotalMoney.toFixed(2),
    })
    console.log(selectItem)
    _this.closePopup()
  },

  //获取用户优惠券数据
  getConponId() {
    var uid = this.data.userInfo.userId;
    //网络请求获取数据
    var _this = this;
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: 'http://43.139.97.111:8080/userCoupon/queryByUserId?userId=' + uid,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res.data);
        if (res.statusCode == 200 && res.data.data != '') {
          _this.setData({
            couponlist: res.data.data,
            haveCoupon: true,
          })
        } else {
          _this.setData({
            haveCoupon: false
          })
        }
        _this.getConpon()
        wx.hideLoading()
      }
    })
  },
  getConpon: function () {
    var _this = this
    console.log(_this.data.couponlist);
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    for (let i = 0; i < _this.data.couponlist.length; i++) {
      console.log(_this.data.couponlist[i].couponId)
      wx.request({
        url: 'http://43.139.97.111:8080/coupon/queryById?id=' + _this.data.couponlist[i].couponId,
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          console.log(res.data);
          if (res.statusCode == 200) {
            _this.setData({
              temp: res.data.data,
            })
            _this.data.userCoupon[i] = _this.data.temp
          }
        }
      })
    }
    setTimeout(() => {
      _this.setData({
        userCoupon: _this.data.userCoupon
      })
    }, 1000)
    wx.hideLoading()
  },


  //提交订单
  SubmitOrder() {
    var _this = this
    let orderPay;
    wx.showModal({
      title: '支付提示',
      content: '请您确定支付',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          orderPay = 1;
          _this.orderData(orderPay)
          //返回购物车并刷新页面
          var pages = getCurrentPages();
          var beforePage = pages[pages.length - 2];
          beforePage.getCart();
          beforePage.backData();
          wx.navigateBack({
            delta: 1,
            success: (res) => { },
            fail: (res) => { },
            complete: (res) => { },
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
          //删除购物车的数据，删除优惠券的数据，生成订单数据(未支付)
          orderPay = 0
          _this.orderData(orderPay)
          wx.showModal({
            title: '提示',
            content: '订单生成成功，您可以前往“我的订单”中取消或支付',
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
                //返回购物车并刷新页面
                var pages = getCurrentPages();
                var beforePage = pages[pages.length - 2];
                beforePage.getCart();
                beforePage.backData();
                wx.navigateBack({
                  delta: 1,
                  success: (res) => { },
                  fail: (res) => { },
                  complete: (res) => { },
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
                //返回购物车并刷新页面
                var pages = getCurrentPages();
                var beforePage = pages[pages.length - 2];
                beforePage.getCart();
                beforePage.backData();
                wx.navigateBack({
                  delta: 1,
                  success: (res) => { },
                  fail: (res) => { },
                  complete: (res) => { },
                })
              }
            }
          })
        }
      }
    })
  },

  orderData(orderPay) {
    console.log(orderPay);
    //删除购物车的数据，删除优惠券的数据，生成订单数据(已支付)
    var _this = this
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    //删除购物车的数据
    for (let i = 0; i < _this.data.paylist.length; i++) {
      //请求删除购物车数据
      wx.request({
        url: 'http://43.139.97.111:8080/cartItem/update',
        data: {
          bookId: _this.data.paylist[i].bookId,
          cartItemId: _this.data.paylist[i].cartItemId,
          userId: _this.data.paylist[i].userId,
          deleteFlag: 1,
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        method: 'PUT',
        success: function (res) {
          console.log("res", res);
        },
        fail: function (res) { },
        complete: function (res) { },
      })
    }
    //删除优惠券的数据
    for (let i = 0; i < _this.data.selectCoupon.length; i++) {
      console.log(_this.data.selectCoupon[i].id)
      wx.request({
        url: 'http://43.139.97.111:8080/userCoupon/update',
        data: {
          deleteFlag: 1,
          id: _this.data.selectCoupon[i].id,
          userId: _this.data.userInfo.userId,
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        method: 'PUT',
        success: function (res) {
          console.log("res", res);
        },
        fail: function (res) { },
        complete: function (res) { },
      })
    }
    //生成订单数据
    var temp = _this.data.paylist[0].cartItemId
    var address = _this.data.address
    var tempAddress = address.addressProvince + address.addressCity + address.addressDetail
    console.log(tempAddress)
    for (let i = 1; i < _this.data.paylist.length; i++) {
      temp = temp + ',' + _this.data.paylist[i].cartItemId
      console.log(temp)
    }
    wx.request({
      url: 'http://43.139.97.111:8080/orderItem/insert',
      data: {
        address: tempAddress,
        name: address.name,
        phone: address.phone,
        cartItems: temp,
        orderPay: orderPay,
        orderTotalPrice: _this.data.totalMoney,
        userId: _this.data.userInfo.userId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: 'POST',
      success: function (res) {
        console.log("res", res);
      },
      fail: function (res) { },
      complete: function (res) { },
    })
    wx.hideLoading()
  },

  //获取地址数据
  getAddress: function () {
    var _this = this
    console.log(_this.data.addressList);
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: 'http://43.139.97.111:8080/address/queryByUserId?userId=' + _this.data.userInfo.userId,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res.data);
        if (res.statusCode == 200 && res.data.data!='') {
          _this.setData({
            addressList: res.data.data,
            haveAddress: true
          })
          _this.data.address = _this.data.addressList[0];
        } else {
          _this.setData({
            haveAddress: false
          })
        }
      }
    })
    setTimeout(() => {
      _this.setData({
        address: _this.data.address
      })
    }, 200)
    wx.hideLoading()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var _this = this
    const userinfo = wx.getStorageSync("userInfo");
    this.setData({
      userInfo: userinfo
    });
    console.log(_this.data.userInfo.userId)
  },
})